﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    osgQt::GraphicsWindowQt* gw = createGraphicsWindow(800, 600);
    const osg::GraphicsContext::Traits* traits = gw->getTraits();
    osg::Camera* camera = _viewer.getCamera();
    camera->setGraphicsContext(gw);
    camera->setClearColor(osg::Vec4(0.3, 0.3, 0.6, 1.0));
    camera->setViewport( new osg::Viewport(0,0,traits->width,traits->height));
    camera->setProjectionMatrixAsPerspective(
                30.0, traits->width / traits->height, 1.0, 10000.0);

    _viewer.addEventHandler( new osgViewer::StatsHandler );
    _viewer.setCameraManipulator( new osgGA::TrackballManipulator );
    _viewer.setThreadingModel( osgViewer::Viewer::SingleThreaded );
    connect( &_timer, SIGNAL(timeout()), this, SLOT(update()));
    _timer.start( 40 );

    setCentralWidget(gw->getGLWidget());
}

MainWindow::~MainWindow()
{
    delete ui;
}

osgQt::GraphicsWindowQt* MainWindow::createGraphicsWindow(int w, int h)
{
    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
    traits->windowDecoration = false;
    traits->x = 0;
    traits->y = 0;
    traits->width = w;
    traits->height = h;
    traits->doubleBuffer = true;

    return new osgQt::GraphicsWindowQt(traits.get());
}

void MainWindow::loadModelFile(const QString &fileName)
{
    std::string modelFile=fileName.toStdString();
    osg::ref_ptr<osg::Node> node=osgDB::readNodeFile(modelFile);
    if(node.get() == 0)
    {
        QMessageBox::warning(this,"不支持的类型",
                             "抱歉，当前不支持该文件类型！");
        return;
    }
    _optimizer.optimize(node.get());
    _viewer.setSceneData(node.get());

    setWindowTitle(QFileInfo(fileName).fileName());
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    _viewer.frame();
}

void MainWindow::on_actionOpen_triggered()
{
    QString path=QFileDialog::getOpenFileName(this,"选择一个文件");
    if(path.isEmpty())
        return;

    if(sp_containChinese(path))
    {
        QMessageBox::warning(this,"不支持的路径",
                             "抱歉，当前不支持中文路径！");
        return;
    }

    loadModelFile(path);
}
